import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CreateFileListDto } from './dto/create-file-list.dto';
import { UpdateFileListDto } from './dto/update-file-list.dto';
import { FileList } from './entities/file-list.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { FileUtil } from '../common/file';
import { request, type Response } from 'express';
import { zip } from 'compressing';
import { promises as fsPromises } from 'fs';
import {
  CreateGroupToFilelistDto,
  RawGroupToFilelistDto,
} from './dto/create-grouptofilelist.dto';
import { GroupToFlielist } from './entities/grouptofilelist.entity';
import * as fs from 'fs';
import { User } from 'src/user/entities/user.entity';
import { usertogroup } from 'src/group/entities/usertogroup.entity';
import * as fsExtra from 'fs-extra';
import { ImagerasterService } from 'src/imageraster/imageraster.service';
import * as path from 'path';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';
@Injectable()
export class FileListService {
  constructor(
    @InjectRepository(FileList)
    private readonly fileListRepository: Repository<FileList>,
    @InjectRepository(GroupToFlielist)
    private readonly groupToFlielistRepository: Repository<GroupToFlielist>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(usertogroup)
    private readonly usertogroupRepository: Repository<usertogroup>,
    private readonly imagerasterService: ImagerasterService,
  ) {}

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  async create(
    createFileListDto: CreateFileListDto,
    file: Express.Multer.File,
  ) {
    if (file.mimetype === 'image/tiff') {
      const file_path = path.resolve(
        `${process.env.FILE_PATH}/${createFileListDto.uploader}/imageraster/${file.filename}`,
      );
      const output_path = path.resolve(
        `${process.env.FILE_PATH}/${
          createFileListDto.uploader
        }/imagerasterTopng/${file.filename.replace('.tif', '.png')}`,
      );
      const destinationPath = path.resolve(
        `${process.env.FILE_PATH}/${createFileListDto.uploader}/imagerasterTopng`,
      );
      if (!fs.existsSync(destinationPath)) {
        fs.mkdirSync(destinationPath, { recursive: true });
      }
      await this.imagerasterService.tif2png(file_path, output_path);
    }
    createFileListDto.src = file.filename;
    createFileListDto.original_name = file.originalname;
    createFileListDto.size = String(file.size);
    createFileListDto.raw_type = file.mimetype;
    const fileList = this.fileListRepository.create(createFileListDto);
    const insertRes = await this.fileListRepository.insert(fileList);
    return (insertRes.raw[0] as any).id;
  }

  async mergeFile(createFileListDto: CreateFileListDto) {
    if (createFileListDto.raw_type === 'image/tiff') {
      try {
        const file_path = path.resolve(
          `${process.env.FILE_PATH}/${createFileListDto.uploader}/imageraster/${createFileListDto.src}`,
        );
        const output_path = path.resolve(
          `${process.env.FILE_PATH}/${
            createFileListDto.uploader
          }/imagerasterTopng/${createFileListDto.src.replace('.tif', '.png')}`,
        );
        const destinationPath = path.resolve(
          `${process.env.FILE_PATH}/${createFileListDto.uploader}/imagerasterTopng`,
        );
        if (!fs.existsSync(destinationPath)) {
          fs.mkdirSync(destinationPath, { recursive: true });
        }
        await this.imagerasterService.tif2png(file_path, output_path);
      } catch (e) {
        this.logger.log(`将tif文件转换为png失败:`, `${e}`);
      }
    }
    const fileList = this.fileListRepository.create(createFileListDto);
    const insertRes = await this.fileListRepository.insert(fileList);
    return insertRes.raw[0];
  }

  async savePlotResult(data: any, email: any) {
    const jsonData = JSON.stringify(data, null, 2); // 格式化 JSON
    const dateTime = new Date().getTime();
    fs.mkdirSync(`${process.env.FILE_PATH}/${email}/application`, {
      recursive: true,
    });
    fs.writeFileSync(
      `${process.env.FILE_PATH}/${email}/application/${dateTime}.json`,
      jsonData,
      'utf-8',
    );
    const createFileListDto = {
      file_name: `标绘结果保存-${new Date().getTime()}`,
      original_name: `标绘结果保存-${new Date().getTime()}`,
      uploader: email,
      folder_id: '-1',
      raw_type: 'application/json',
      src: `${dateTime}.json`,
      size: Buffer.byteLength(jsonData, 'utf-8').toString(),
    };
    const fileList = this.fileListRepository.create(createFileListDto);
    const insertRes = await this.fileListRepository.insert(fileList);
    return insertRes.raw[0];
  }

  async createGroupSingleDBRecord(
    createFileListDto: CreateFileListDto,
    groupuuid: any,
  ) {
    const fileuuid = await this.createSingleDBRecord(createFileListDto);
    const createGroupToFilelistDto = new CreateGroupToFilelistDto();
    createGroupToFilelistDto.fileuuid = fileuuid;
    createGroupToFilelistDto.groupuuid = groupuuid;
    createGroupToFilelistDto.belong = createFileListDto.uploader;
    this.moveFileItemToGroup(createGroupToFilelistDto);
    return '上传成功';
  }
  async createSingleDBRecord(createFileListDto: CreateFileListDto) {
    const fileList = this.fileListRepository.create(createFileListDto);
    const insertRes = await this.fileListRepository.insert(fileList);
    return insertRes.raw[0];
  }

  async createSingleRecord(createFileListDto: CreateFileListDto) {
    const fileList = this.fileListRepository.create(createFileListDto);
    const insertRes = await this.fileListRepository.insert(fileList);
    return (insertRes.raw[0] as any).id;
  }

  findAll() {
    return `This action returns all fileList`;
  }

  async getAllFileItemByUser(uploader: string): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.role != :role', { role: 'group' })
      .getMany();
  }

  findOne(id: string) {
    return this.fileListRepository.findOne({ where: { id: id } });
  }

  async getByTypeAndFileIds(
    type: string,
    fileIds: string[],
  ): Promise<FileList[]> {
    if (type === 'raster') {
      type = 'image/tiff'; // 兼容raster
    }
    // const data = await this.fileListRepository
    //   .createQueryBuilder('file_list')
    //   .where('file_list.raw_type LIKE :prefix', { prefix: `${type}%` })
    //   .andWhere('file_list.id IN (:...fileIds)', { fileIds })
    //   .getMany();
    let query = this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.id IN (:...fileIds)', { fileIds });
    if (type === 'image') {
      query = query
        .andWhere('file_list.raw_type LIKE :imageType', {
          imageType: 'image/%',
        })
        .andWhere('file_list.raw_type NOT LIKE :imageTiffType', {
          imageTiffType: 'image/tiff%',
        });
    } else {
      query = query.andWhere('file_list.raw_type LIKE :prefix', {
        prefix: `${type}%`,
      });
    }
    const data = await query.getMany();
    return data;
  }

  async update(id: string, updateFileListDto: UpdateFileListDto) {
    const oldFile = await this.fileListRepository.findOne({
      where: { id: id },
    });
    if (!oldFile) {
      return '未找到匹配的记录，没有进行更新操作';
    }
    try {
      const updateFlie = this.fileListRepository.merge(
        oldFile,
        updateFileListDto,
      );
      await this.fileListRepository.save(updateFlie);
      return '修改文件属性成功!';
    } catch (err) {
      throw new BadRequestException('更新文件条目失败');
    }
  }

  async remove(id: string) {
    // // 判断 role 是不是 person
    const fileItem = await this.fileListRepository.findOne({
      where: { id: id },
    });
    // if (fileItem.role === 'person' || fileItem.role === 'group') {
    try {
      const result = await this.fileListRepository.delete({ id: id });
      // 判断
      const fileList = await this.fileListRepository.find({
        where: {
          src: fileItem.src,
        },
      });
      if (fileList.length === 0) {
        let folder = 'other'; // 默认文件夹名
        if (fileItem.raw_type.startsWith('image/')) {
          if (fileItem.raw_type === 'image/tiff') {
            folder = 'imageraster';
          } else {
            folder = 'images';
          }
        } else if (fileItem.raw_type.startsWith('audio/')) {
          folder = 'audios';
        } else if (fileItem.raw_type.startsWith('video/')) {
          folder = 'videos';
        } else if (fileItem.raw_type.startsWith('text/')) {
          folder = 'text';
        } else if (fileItem.raw_type.startsWith('application/')) {
          folder = 'application';
        }
        const fileName = path.resolve(
          process.env.FILE_PATH +
            '/' +
            fileItem.uploader +
            '/' +
            folder +
            '/' +
            fileItem.src,
        );
        if (result.affected && result.affected > 0) {
          await FileUtil.deleteLocalFile(fileName);
          if (folder === 'imageraster') {
            const imagerasterPath = path.resolve(
              `${process.env.FILE_PATH}/${
                fileItem.uploader
              }/imagerasterTopng/${fileItem.src.replace('.tif', '.png')}`,
            );
            await FileUtil.deleteLocalFile(imagerasterPath);
          }
          return `成功删除 ${result.affected} 条记录`;
        } else {
          return `未找到匹配的记录，没有进行删除操作`;
        }
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }

  async downloadFileItem(id: string, response: Response) {
    try {
      const res = await this.fileListRepository.findOne({
        where: { id: id },
      });
      let folder = '';
      if (res.raw_type.startsWith('image/')) {
        if (res.raw_type === 'image/tiff') {
          folder = 'imageraster';
        } else {
          folder = 'images';
        }
      } else if (res.raw_type.startsWith('audio/')) {
        folder = 'audios';
      } else if (res.raw_type.startsWith('video/')) {
        folder = 'videos';
      } else if (res.raw_type.startsWith('text/')) {
        folder = 'text';
      } else if (res.raw_type.startsWith('application/')) {
        folder = 'application';
      }
      const destinationPath = path.resolve(
        `${process.env.FILE_PATH}/${res.uploader}/${folder}/${res.src}`,
      );
      response.download(destinationPath);
    } catch (err) {
      console.error('下载记录失败', err);
      throw '下载记录失败';
    }
  }

  async downloadFileItemStream(id: string, response: Response) {
    try {
      const res = await this.fileListRepository.findOne({
        where: { id: id },
      });
      if (!res) {
        throw new Error('File not found');
      }

      let folder = 'other';
      if (res.raw_type.startsWith('image/')) {
        folder = res.raw_type === 'image/tiff' ? 'imageraster' : 'images';
      } else if (res.raw_type.startsWith('audio/')) {
        folder = 'audios';
      } else if (res.raw_type.startsWith('video/')) {
        folder = 'videos';
      } else if (res.raw_type.startsWith('text/')) {
        folder = 'text';
      } else if (res.raw_type.startsWith('application/')) {
        folder = 'application';
      }

      const filePath = path.resolve(
        `${process.env.FILE_PATH}/${res.uploader}/${folder}/${res.src}`,
      );

      // Set appropriate headers
      response.setHeader('Content-Type', res.raw_type);
      response.setHeader(
        'Content-Disposition',
        `attachment; filename="${encodeURIComponent(res.src)}"`,
      );

      // Stream the file directly
      const fileStream = fs.createReadStream(filePath);
      fileStream.pipe(response);
    } catch (err) {
      console.error('下载记录失败', err);
      response.status(500).send('下载记录失败');
    }
  }

  async getFileItemContent(id: string, response: Response) {
    const res = await this.fileListRepository.findOne({
      where: { id: id },
    });
    if (res) {
      let folder = '';
      if (res.raw_type.startsWith('image/')) {
        if (res.raw_type === 'image/tiff') {
          folder = 'imagerasterTopng';
          res.raw_type = 'image/png';
        } else {
          folder = 'images';
        }
      } else if (res.raw_type.startsWith('audio/')) {
        folder = 'audios';
        // response.setHeader('Cache-Control', 'public, max-age=31536000'); // 设置缓存有效期为一年
        // response.setHeader(
        //   'Expires',
        //   new Date(Date.now() + 31536000000).toUTCString(),
        // ); // 设置过期时间为一年后
      } else if (res.raw_type.startsWith('video/')) {
        folder = 'videos';
      } else if (res.raw_type.startsWith('text/')) {
        folder = 'text';
      } else if (res.raw_type.startsWith('application/')) {
        folder = 'application';
      }
      const destinationPath = path.resolve(
        `${process.env.FILE_PATH}/${res.uploader}/${folder}/${res.src.replace(
          '.tif',
          '.png',
        )}`,
      );
      const stats = await fsPromises.stat(destinationPath);
      response.setHeader('Content-Type', res.raw_type);
      response.setHeader('Content-Length', stats.size.toString());
      response.setHeader('Accept-Ranges', 'bytes');
      response.set('Cache-Control', 'public, max-age=3600');
      response.set('Last-Modified', new Date().toUTCString()); // 缓存1小时

      const fileStream = fs.createReadStream(destinationPath);
      fileStream.pipe(response);
    }
  }

  async createFileItemToGroup(
    createFileListDto: CreateFileListDto,
    file: Express.Multer.File,
    groupuuid: string,
  ) {
    createFileListDto.role = 'group';
    const fileuuid = await this.create(createFileListDto, file);
    const createGroupToFilelistDto = new CreateGroupToFilelistDto();
    createGroupToFilelistDto.fileuuid = fileuuid;
    createGroupToFilelistDto.groupuuid = groupuuid;
    createGroupToFilelistDto.belong = createFileListDto.uploader;
    this.moveFileItemToGroup(createGroupToFilelistDto);
    return '上传成功';
  }
  async mergeGroupFile(
    createFileListDto: CreateFileListDto,
    groupuuid: string,
  ) {
    const fileuuid = await this.mergeFile(createFileListDto);
    const createGroupToFilelistDto = new CreateGroupToFilelistDto();
    createGroupToFilelistDto.fileuuid = fileuuid.id;
    createGroupToFilelistDto.groupuuid = groupuuid;
    createGroupToFilelistDto.belong = createFileListDto.uploader;
    this.moveFileItemToGroup(createGroupToFilelistDto);
    return '上传成功';
  }

  async deleteFileItemFromGroup(fileuuid: string) {
    try {
      const result = await this.groupToFlielistRepository.delete({
        fileuuid: fileuuid,
      });
      await this.remove(fileuuid);
      if (result.affected && result.affected > 0) {
        return `成功删除 ${result.affected} 条记录`;
      } else {
        return `未找到匹配的记录，没有进行删除操作`;
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }
  // 类型需要从新修改
  async getFileItemByGroupuuid(groupuuid: string) {
    const fileItemList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const filePromises = fileItemList.map(async (fileItem) => {
      const fileInfo = await this.fileListRepository.findOne({
        where: { id: fileItem.fileuuid },
      });

      if (fileInfo) {
        const userItem = await this.userRepository.findOne({
          where: { email: fileItem.belong },
        });
        const usertogroupItem = await this.usertogroupRepository.findOne({
          where: { useruuid: userItem?.id, groupuuid: groupuuid },
        });
        (fileInfo as any).uploader_nickname = usertogroupItem?.groupnickname;
        (fileInfo as any).fileToGroupId = fileItem.id;
        return fileInfo;
      } else {
        return null;
      }
    });
    const fileItemOfGroupList = await Promise.all(filePromises);
    return fileItemOfGroupList.filter((file) => file !== null) as FileList[];
  }

  async getFileItemByGroupuuidFolderuuid(
    groupuuid: string,
    folderuuid: string,
  ) {
    const fileItemList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const filePromises = fileItemList.map(async (fileItem) => {
      const fileInfo = await this.fileListRepository.findOne({
        where: { id: fileItem.fileuuid, folder_id: folderuuid },
      });

      if (fileInfo) {
        const userItem = await this.userRepository.findOne({
          where: { email: fileItem.belong },
        });
        const usertogroupItem = await this.usertogroupRepository.findOne({
          where: { useruuid: userItem?.id, groupuuid: groupuuid },
        });
        (fileInfo as any).uploader_nickname = usertogroupItem?.groupnickname;
        (fileInfo as any).fileToGroupId = fileItem.id;
        return fileInfo;
      } else {
        return null;
      }
    });
    const fileItemOfGroupList = await Promise.all(filePromises);
    return fileItemOfGroupList.filter((file) => file !== null) as FileList[];
  }

  async moveFileItemToGroup(createGroupToFilelistDto: RawGroupToFilelistDto) {
    const insertItem = this.groupToFlielistRepository.create(
      createGroupToFilelistDto,
    );
    this.groupToFlielistRepository.insert(insertItem);
    return `已经放置小组共享空间`;
  }

  async getPicFileItemByUserInPerson(
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'image/%' })
      .andWhere('file_list.raw_type NOT LIKE :excludeType', {
        excludeType: 'image/tiff',
      })
      .getMany();
  }

  async getPicFileItemByUserInGroup(
    groupuuid: string,
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    const groupFileList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const fileUuids = groupFileList.map((item) => item.fileuuid); // 获取所有 groupFileList 中的 fileuuid

    // 如果 fileUuids 为空，直接返回空数组
    if (fileUuids.length === 0) {
      return [];
    }
    // 使用 fileUuids 进行后续查询
    const result = await this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.id IN (:...fileUuids)', { fileUuids }) // 使用 IN 条件查询
      .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'image/%' })
      .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
      .andWhere('file_list.raw_type NOT LIKE :excludeType', {
        excludeType: 'image/tiff',
      })
      .getMany();

    return result;
  }

  async getAllPicFileItemByUserInGroup(groupuuid: string, email: any) {
    const groupFileList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const fileUuids = groupFileList.map((item) => item.fileuuid); // 获取所有 groupFileList 中的 fileuuid
    // 如果 fileUuids 为空，直接返回空数组
    if (fileUuids.length === 0) {
      return [];
    }
    // 使用 fileUuids 进行后续查询
    const result = await this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.id IN (:...fileUuids)', { fileUuids }) // 使用 IN 条件查询
      .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'image/%' })
      .andWhere('file_list.raw_type NOT LIKE :excludeType', {
        excludeType: 'image/tiff',
      })
      .getMany();

    return result;
  }
  getAllPicFileItemByUserInPerson(uploader: any) {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'image/%' })
      .andWhere('file_list.raw_type NOT LIKE :excludeType', {
        excludeType: 'image/tiff',
      })
      .getMany();
  }

  async getVidFileItemByUserInPerson(
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'video/%' })
      .getMany();
  }

  async getVidFileItemByUserInGroup(
    groupuuid: string,
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    const groupFileList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const fileUuids = groupFileList.map((item) => item.fileuuid); // 获取所有 groupFileList 中的 fileuuid
    // 如果 fileUuids 为空，直接返回空数组
    if (fileUuids.length === 0) {
      return [];
    }
    return (
      this.fileListRepository
        .createQueryBuilder('file_list')
        // .where('file_list.uploader = :uploader', { uploader })
        .where('file_list.id IN (:...fileUuids)', { fileUuids }) // 使用 IN 条件查询
        .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
        .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'video/%' })
        .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
        .getMany()
    );
  }

  async getAudFileItemByUserInPerson(
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'audio/%' })
      .getMany();
  }

  async getAudFileItemByUserInGroup(
    groupuuid: string,
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    const groupFileList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const fileUuids = groupFileList.map((item) => item.fileuuid); // 获取所有 groupFileList 中的 fileuuid
    // 如果 fileUuids 为空，直接返回空数组
    if (fileUuids.length === 0) {
      return [];
    }
    return (
      this.fileListRepository
        .createQueryBuilder('file_list')
        .where('file_list.id IN (:...fileUuids)', { fileUuids }) // 使用 IN 条件查询
        // .where('file_list.uploader = :uploader', { uploader })
        .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
        .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
        .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'audio/%' })
        .getMany()
    );
  }

  async getTxtFileItemByUserInPerson(uploader: string): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'text/%' })
      .getMany();
  }

  async getTxtFileItemByUserInGroup(uploader: string): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
      .andWhere('file_list.raw_type LIKE :prefix', { prefix: 'text/%' })
      .getMany();
  }

  async getJsonFileItemByUserInPerson(
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type = :upload', { upload: 'application/json' })
      .getMany();
  }

  async getJsonFileItemByUserInGroup(
    groupuuid: string,
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    const groupFileList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const fileUuids = groupFileList.map((item) => item.fileuuid); // 获取所有 groupFileList 中的 fileuuid
    // 如果 fileUuids 为空，直接返回空数组
    if (fileUuids.length === 0) {
      return [];
    }
    return (
      this.fileListRepository
        .createQueryBuilder('file_list')
        .where('file_list.id IN (:...fileUuids)', { fileUuids }) // 使用 IN 条件查询
        // .where('file_list.uploader = :uploader', { uploader })
        .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
        .andWhere('file_list.raw_type = :type', { type: 'application/json' })
        .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
        .getMany()
    );
  }

  async getRasterFileItemByUserInPerson(
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    return this.fileListRepository
      .createQueryBuilder('file_list')
      .where('file_list.uploader = :uploader', { uploader })
      .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
      .andWhere('file_list.role IN (:...roles)', { roles: ['person'] })
      .andWhere('file_list.raw_type = :upload', { upload: 'image/tiff' })
      .getMany();
  }

  async getRasterFileItemByUserInGroup(
    groupuuid: string,
    folderuuid: string,
    uploader: string,
  ): Promise<FileList[]> {
    const groupFileList = await this.groupToFlielistRepository.find({
      where: { groupuuid: groupuuid },
    });
    const fileUuids = groupFileList.map((item) => item.fileuuid); // 获取所有 groupFileList 中的 fileuuid
    // 如果 fileUuids 为空，直接返回空数组
    if (fileUuids.length === 0) {
      return [];
    }
    return (
      this.fileListRepository
        .createQueryBuilder('file_list')
        .where('file_list.id IN (:...fileUuids)', { fileUuids }) // 使用 IN 条件查询
        // .where('file_list.uploader = :uploader', { uploader })
        .andWhere('file_list.role IN (:...roles)', { roles: ['group'] })
        .andWhere('file_list.raw_type = :type', { type: 'image/tiff' })
        .andWhere('file_list.folder_id = :folderuuid', { folderuuid })
        .getMany()
    );
  }

  getFileItemUserByFolderuuid(folderuuid: string, email: any) {
    return this.fileListRepository.find({
      where: {
        folder_id: folderuuid,
        uploader: email,
        role: 'person',
      },
    });
  }

  async getChildFileByFolderuuid(folderuuid: string) {
    const res = await this.fileListRepository.find({
      where: {
        folder_id: folderuuid,
      },
      select: ['id'],
    });
    return res.map((item) => ({ ...item, type: 'file' }));
  }

  async copyFileItemToGroup(
    fileuuid: string,
    folderuuid: string,
    groupuuid: string,
    email: any,
  ) {
    const findFileItem = await this.findOne(fileuuid);
    if (findFileItem) {
      const { id, ...otherproperties } = findFileItem;
      otherproperties.folder_id = folderuuid;
      otherproperties.uploader = email;
      otherproperties.role = 'group';
      const insertItem = this.fileListRepository.create(otherproperties);
      const insertRes = await this.fileListRepository.insert(insertItem);
      await this.moveFileItemToGroup({
        fileuuid: insertRes.identifiers[0].id,
        groupuuid: groupuuid,
        belong: email,
      });
      return `已经复制文件到共享空间`;
    } else {
      return `文件不存在`;
    }
  }
  async copyFileItemToUser(fileuuid: string, folderuuid: string, email: any) {
    const findFileItem = await this.findOne(fileuuid);
    if (findFileItem) {
      const { id, ...otherproperties } = findFileItem;
      otherproperties.folder_id = folderuuid;
      otherproperties.uploader = email;
      otherproperties.role = 'person';
      const insertItem = this.fileListRepository.create(otherproperties);
      this.fileListRepository.insert(insertItem);
      return `已经复制文件到个人空间`;
    } else {
      return `文件不存在`;
    }
  }
}
